package com.hh.test.design.proxy.jdkproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkProxy {

	interface IUserDao {
		void save(String user);
	}

	class UserDao implements IUserDao {
		public void save(String user) {
			System.out.println("user is " + user);
		}
	}

	public static void main(String[] args) {
		UserDao dao = new JdkProxy().new UserDao();
		IUserDao userProxy = (IUserDao) new JdkProxy().new ProxyFactory(dao)
				.getProxyInstance();
		System.out.println(userProxy.getClass());
		userProxy.save("1");
	}

	class ProxyFactory {
		Object proxy;

		ProxyFactory(Object userDao) {
			this.proxy = userDao;
		}

		Object getProxyInstance() {
			return (Object) Proxy.newProxyInstance(proxy.getClass()
					.getClassLoader(), proxy.getClass().getInterfaces(),
					new InvocationHandler() {

						public Object invoke(Object obj, Method method,
								Object[] aobj) throws Throwable {
							System.out.println("jdk proxy begin");
							Object returnValue = method.invoke(proxy, aobj);
							System.out.println("jdk proxy end");

							return returnValue;
						}
					});

		}

	}

}
